package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoExamineService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * ClassName: WmNewsTaskServiceImpl
 * Description:
 * date: 2023/8/16 0016 15:31
 *
 * @author zHan
 */

@Service
@Slf4j
@Transactional
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient scheduleClient;

    @Autowired
    private WmNewsAutoExamineService wmNewsAutoExamineService;

    /**
     * 添加任务到延迟队列中
     *
     * @param id
     * @param publishTime
     */
    @Override
    @Async  // 异步调用
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("添加任务到延时任务中 ---begin");
        // 创建task对象
        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        // 创建文章对象
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        // 序列化
        byte[] bytes = ProtostuffUtil.serialize(wmNews);
        task.setParameters(bytes);
        // 添加任务
        scheduleClient.addTask(task);

        log.info("添加任务到延时任务中 ---end");

    }

    /**
     * 消费任务，审核文章
     */
    @Override
    @Scheduled(fixedRate = 1000)    // 每秒拉取一次
    public void examineNewsByTask() {

//        log.info("消费任务，审核文章");
        // 拉取任务
        ResponseResult responseResult =
                scheduleClient.pullTask(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(),
                        TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (responseResult.getCode().equals(200) && responseResult.getData() != null) {
            // 将返回的json转换为string
            String json = JSON.toJSONString(responseResult.getData());
            // 将string转换为task
            Task task = JSON.parseObject(json, Task.class);
            // 获取wmNews的id
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
            // 调用自动审核方法
            wmNewsAutoExamineService.autoExamineWmNews(wmNews.getId());
        }
    }
}
